<template>
	<view style="width: 95%;margin: auto;">
		<view class="form_box">
			<view class="form_item">
				<view class="label">车辆品牌</view>
				<input class="input_style" type="text" v-model="form.name" clearable height="92" placeholder="请输入" />
			</view>
			<view class="form_item">
				<view class="label">车辆价格</view>
				<input class="input_style" type="number" v-model="form.price" clearable height="92" placeholder="请输入" />
			</view>

			<view class="form_item" v-if="type == 1">
				<view class="label">首付比例</view>
				<picker :range="options.map(t=>t.label)" @change="(e)=>setPickValue(e.detail.value,'downPayRatio')">
					<view class="pick_box">
						<view :class="form.select ? 'select_state' : 'select_no'">{{form.select || '请选择首付比例'}}</view>
						<image src="../../static/arrow.png" style="width: 28rpx;height: 28rpx;"></image>
					</view>
				</picker>

			</view>
			<view class="form_item">
				<view class="label">还款期限</view>
				<view class="readonly">36期</view>
			</view>
			<view class="form_item">
				<view class="label">还款方式</view>
				<view class="readonly">等额本息</view>

			</view>
			<view class="form_item">
				<view class="label">年利率</view>
				<!-- <view class="readonly">{{'21.72%' }}</view> -->
				<input class="input_style" type="digit" v-model="form.ratio" clearable height="92"
					placeholder="请输入年利率，如 : 21.72" />

			</view>
		</view>
		<view style="height: 304rpx;">
		</view>
		<view class="bottom_style_box">
			<view class="submit_buttom" @click="onSubmit">开始计算</view>
			<!-- 	<button v-if="!phoneBol" style="position: fixed;left: 20rpx;right: 0;bottom: 8%;" class="buttom_authorize" scope="phoneNumber"
				open-type="getAuthorize" @getAuthorize="getAuthorize" size="mini" @error="onAuthError"></button> -->
		</view>
		<view class="dialog_box" v-if="visible">
			<view class="content_box">
				<view class="top_line"></view>
				<view class="buttom_box">
					<view class="title">计算结果</view>
					<view class="item" v-if="type == 1">
						<view>首期付款</view>
						<view>{{results.downPay}}元</view>
					</view>
					<view class="item">
						<view>每月还款</view>
						<view>{{results.repayment}}元</view>
					</view>
					<view class="item">
						<view>利息合计</view>
						<view>{{results.interest}}元</view>
					</view>
					<view class="item">
						<view>还款总额</view>
						<view>{{results.total}}元</view>
					</view>
				</view>

			</view>
			<view :style="{display: 'flex',justifyContent: 'center',marginTop: type == 1 ? '67%' : '53%'}"
				@click="onClose">
				<image src="../../static/close_icon.png" style="width: 80rpx;height: 80rpx;"></image>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		requsetGet
	} from '../../utils/request';

	function payOne(rate, year, cost) {
		let realYearRate = rate / 100
		let monthRate = realYearRate / 12;
		let monthPay = ((cost * monthRate * Math.pow(1 + monthRate, year * 12)) / (Math.pow(1 + monthRate, year * 12) -
			1));
		let totalPay = (monthPay * year * 12);
		let totalInterest = (totalPay - cost);
		let result = {
			cost,
			year,
			rate,
			monthRate,
			monthPay,
			totalPay,
			totalInterest
		};
		return result;
	}

	export default {
		data() {
			return {
				form: {
					select: ''
				},
				type: null,
				visible: false,
				results: {
					downPay: 0, // 首付
					repayment: 0, // 还款
					interest: 0, // 利息
					total: 0, // 总还款金额
					ratio: 0 // 利率
				},
				options: [{
						label: '10%',
						value: 0.10,
					},
					{
						label: '20%',
						value: 0.20,
					},
					{
						label: '30%',
						value: 0.30,
					},
					{
						label: '40%',
						value: 0.40,
					},
					{
						label: '50%',
						value: 0.50,
					},
					{
						label: '60%',
						value: 0.60,
					}
				],
				userBol: true,
				addressBol: false,
				phoneBol: false, // 隐藏授权
			};
		},
		onLoad(option) {
			this.type = option.type;
		},
		mounted() {
			// #ifdef APP-PLUS
			this.getLocation();
			// #endif
			// try {
			// 	// 判断是否授权过
			// 	await this.getStorageValue('user');
			// 	await this.getStorageValue('phone');

			// } catch (error) {
			// 	uni.navigateBack({
			// 		delta: 1
			// 	});
			// }
		},
		methods: {
			async onSubmit() {
				// #ifdef APP-PLUS
				if (!this.addressBol && this.userBol) await this.getLocation();
				// #endif
				// if (this.userBol && this.addressBol) {
				const values = {
					...this.form,
					periods: 3
				}
				values.ratio = Number(values.ratio);
				if (!values.name) return uni.showToast({
					title: '请输入车辆品牌',
					icon: 'none'
				});
				if (this.type == 1) {
					// 车辆价格
					if (!values.price) return uni.showToast({
						title: '请输入车辆价格',
						icon: 'none'
					});
				} else {
					if (!values.price) return uni.showToast({
						title: '请输入评估贷款金额',
						icon: 'none'
					});
				};
				let downPay = Number(values.price);
				if (this.type == 1) downPay = Number(values.price) * values.downPayRatio;
				const data = payOne(values.ratio, values.periods, downPay);
				this.results = {
					downPay: downPay.toFixed(2), // 首付
					repayment: data.monthPay.toFixed(2), // 月还还款
					interest: data.totalInterest.toFixed(2), //总和 利息
					total: data.totalPay.toFixed(2), // 总还款金额
				};
				this.visible = true;
				// } else {
				// 	this.showModel('未授权用户信息无法正常使用计算器');
				// }

			},
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						success: async (res) => {
							const location = {
								latitude: res.latitude,
								longitude: res.longitude
							};
							await requsetGet('AlipayController/getAddressByJwd', location).then(
								async (res) => {
									const {
										province,
										city,
										district
									} = res.data.result.address_component;
									const user = await this.getStorageValue('user');
									const data = {
										phone: await this.getStorageValue('phone'),
										czdssq: [province, city, district].join('-'),
										...user,
										appType: await this.appTypeResult()
									};
									await requsetGet('/AlipayController/registerUser', data);
									this.addressBol = true;
									resolve(true);
								});
						},
						fail: (err) => {
							reject(false);
							this.showModel(false, 'location');
						}
					})
				})
			},
			// key如果一样就只需要传key  如果key值跟获取值不一样传getValueKey
			getStorageValue(key, getValueKey) {
				return new Promise((resolve, reject) => {
					uni.getStorage({
						key,
						success({
							data
						}) {
							if (!data) return reject(new Error(`未找到该${key}数据`));
							if (getValueKey) resolve(data[getValueKey])
							else resolve(data[key])
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			showModel(message, key) {
				uni.showModal({
					title: '提示',
					content: message || '取消授权，可能会影响部分服务无法使用，或页面不完整性',
					cancelText: '我知道了',
					confirmText: '重新授权',
					success: (res) => {
						if (res.confirm) {
							if (key === 'location') {
								my.openSetting({
									success: (res) => {
										res.authSetting.location && this.getLocation();
									}
								})
							}

						}
					}
				})
			},
			getUserCode() {
				return new Promise((resolve, reject) => {
					my.getAuthCode({
						scopes: ['auth_user'],
						success: async (res) => {
							const {
								data
							} = await requsetGet('AlipayController/getAlipayuserByCode', {
								code: res.authCode,
								appType: await this.appTypeResult(),
							});
							const user = {
								nickName: data.nickName,
								avatar: data.avatar,
								userId: data.userId
							}
							uni.setStorage({
								key: 'user',
								data: {
									user
								}
							});
							this.userBol = true;
							resolve(true)
						},
						fail: (err) => {
							reject(false);
							uni.hideLoading();
							this.showModel();
						}
					})
				})
			},
			getAuthorize(type) {
				my.getPhoneNumber({
					success: async (res) => {
						// uni.showLoading({
						// 	title: '获取授权中'
						// })
						requsetGet('AlipayController/decryptPhone', {
							phoneEncryptedStr: res.response,
							appType: await this.appTypeResult()
						}).then(async ({
							data
						}) => {
							uni.setStorage({
								key: 'phone',
								data: {
									phone: data.mobile
								}
							});
							this.phoneBol = true;
							// if (!this.userBol) await this.getUserCode();
							this.getLocation(); // 提交用户数据
							// uni.hideLoading();
						})
					}
				})
			},
			onAuthError(err) {
				// uni.hideLoading();
				this.showModel()
			},
			onClose() {
				this.visible = false;
			},
			setPickValue(index, key) {
				this.form.select = this.options[index].label;
				this.form[key] = this.options[index].value;
			},
		}
	}
</script>
<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss">
	@import "index.scss";

	.buttom_authorize {
		position: absolute;
		opacity: 0;
		left: 0;
		right: 0;
		height: 92rpx;
		width: 92%;
	}
</style>